package com.uenpay.util.common;

import android.text.TextUtils;

import java.util.Collection;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class VerifyUtils {

	/**
	 *  判断对象或对象数组中每一个对象是否为空: 对象为null，字符序列长度为0，集合类、Map为empty
	 *  集合中有一个元素为空，则返回true
	 *
	 * @param obj
	 * @return
	 */
	public static boolean isNullOrEmpty(Object obj) {
		if (obj == null)
			return true;

		if (obj instanceof CharSequence)
			return ((CharSequence) obj).length() == 0;

		if (obj instanceof Collection)
			return ((Collection<?>) obj).isEmpty();

		if (obj instanceof Map)
			return ((Map<?, ?>) obj).isEmpty();

		if (obj instanceof Object[]) {
			Object[] object = (Object[]) obj;
			if (object.length == 0) {
				return true;
			}
			boolean empty = false;
			for (int i = 0; i < object.length; i++) {
				if (isNullOrEmpty(object[i])) {
					empty = true;
					break;
				}
			}
			return empty;
		}
		return false;
	}

	public static boolean isNumeric(String str) {
		for (int i = str.length(); --i >= 0;) {
			if (!Character.isDigit(str.charAt(i))) {
				return false;
			}
		}
		return true;
	}

	// 判断身份证号码的合法性
	public static int verifyIDCard(String IdStr) {
		if (IdStr.length() != 18)
			return 1;
		int i;
		for (i = 0; i < 17; i++) {
			if (IdStr.charAt(i) < '0' || IdStr.charAt(i) > '9')
				return 2;
		}
		if (IdStr.charAt(17) == 'x' ||IdStr.charAt(17) == 'X'
				|| (IdStr.charAt(17) >= '0' && IdStr.charAt(17) <= '9'))
			;
		else
			return 3;

		String year = IdStr.substring(6, 10);
		int year_number = Integer.parseInt(year);
		if (year_number < 1900 || year_number > 2100)
			return 4;

		String month = IdStr.substring(10, 12);
		int month_number = Integer.parseInt(month);
		if (month_number < 1 || month_number > 12)
			return 5;

		String day = IdStr.substring(12, 14);
		int day_number = Integer.parseInt(day);
		if (((year_number % 4 == 0) && (year_number % 100 != 0))
				|| (year_number % 400 == 0)) {
			if (2 == month_number) {
				if (day_number < 1 || day_number > 29)
					return 6;
			} else if (month_number == 1 || month_number == 3
					|| month_number == 5 || month_number == 7
					|| month_number == 8 || month_number == 10
					|| month_number == 12) {
				if (day_number < 1 || day_number > 31)
					return 6;
			} else {
				if (day_number < 1 || day_number > 30)
					return 6;
			}
		} else {
			if (month_number == 2) {
				if (day_number < 1 || day_number > 28)
					return 6;
			} else if (month_number == 1 || month_number == 3
					|| month_number == 5 || month_number == 7
					|| month_number == 8 || month_number == 10
					|| month_number == 12) {
				if (day_number < 1 || day_number > 31)
					return 6;
			} else {
				if (day_number < 1 || day_number > 30)
					return 6;
			}
		}
		return 0;
	}

	// 判断信用卡号的合法性
	public static boolean verifyAccountCard(String sCard) {
		String reCard = "^(4\\d{12}(?:\\d{3})?)$";
		Pattern com = Pattern.compile(reCard);
		Matcher mat = com.matcher(sCard);
		//格式正确
		if (mat.find()) {
			// 判断是否合法
			boolean luhn = VerifyUtils.isLuhn(sCard);
			if (luhn) {
				//卡号合法
				return true;
			} else {
				return false;
			}
		}
		return false;
	}

	  /**
     * 校验银行卡卡号
     * @param cardId
     * @return
     */
    public static boolean checkBankCard(String cardId) {
//    		 char bit = getBankCardCheckCode(cardId.substring(0, cardId.length() - 1));
//    		 if(bit == 'N'){
//    			 return false;
//    		 }
//    		 return cardId.charAt(cardId.length() - 1) == bit;
		return validateBankCard(cardId);
    }

    /**
     * 从不含校验位的银行卡卡号采用 Luhm 校验算法获得校验位
     * @param nonCheckCodeCardId
     * @return
     */
    public static char getBankCardCheckCode(String nonCheckCodeCardId){
        if(nonCheckCodeCardId == null || nonCheckCodeCardId.trim().length() == 0
                || !nonCheckCodeCardId.matches("\\d+")) {
        	//如果传的不是数据返回N
            return 'N';
        }
        char[] chs = nonCheckCodeCardId.trim().toCharArray();
        int luhmSum = 0;
        for(int i = chs.length - 1, j = 0; i >= 0; i--, j++) {
            int k = chs[i] - '0';
            if(j % 2 == 0) {
                k *= 2;
                k = k / 10 + k % 10;
            }
            luhmSum += k;
        }
        return (luhmSum % 10 == 0) ? '0' : (char)((10 - luhmSum % 10) + '0');
    }


	/**
	 * luhn算法
	 */
	public static boolean isLuhn(String strNum) {

		int oddSum = 0;
		int evenSum = 0;
		boolean isOdd = true;
		for (int i = strNum.length() - 1; i >= 0; i--) {
			char cNum = strNum.charAt(i);
			int num = Integer.parseInt(cNum + "");
			if (isOdd) {
				oddSum += num;
			} else {
				num = num * 2;
				if (num > 9) {
					num = num % 10 + 1;
				}
				evenSum = evenSum + num;
			}
			isOdd = !isOdd;
		}
		return ((evenSum + oddSum) % 10 == 0);
	}

	public static boolean verifyVerCode() {
		return false;
	}

	public static boolean IsUnLegal(String str) {
		String regEx = "[\n\t`~!@#$%^&*()+=|{}':;',\\[\\].<>/?~！@#￥%……&*（）——+|{}【】‘；：”“’。，、？]";
		Pattern p = Pattern.compile(regEx);
		Matcher m = p.matcher(str);
		if (m.find()) {
			return true;
		} else {
			return false;
		}
	}

	/**
	 * 检查电话号码格式
	 * @param str 电话号码
	 * @return 是否为正确格式
	 */
	public static boolean verifyPheNumber(String str) {
		if(null == str || "".equals(str)){
			return false;
		}
		if(str.length()!= 11){
			return false;
		}
		if(!(str.charAt(0) == '1')){
			return false;
		}
		for (int i = str.length(); --i >= 0;) {
			if (!Character.isDigit(str.charAt(i))) {
				return false;
			}
		}
		return true;
	}

	/**
	 * 匹配短信中间的6个数字（验证码等）
	 *
	 * @param patternContent 短信内容 patternCoder 正则表达式
	 * @return
	 */
	public static String patternCode(String patternContent, String patternCoder) {
		if (TextUtils.isEmpty(patternContent)) {
			return null;
		}
		Pattern p = Pattern.compile(patternCoder);
		Matcher matcher = p.matcher(patternContent);
		if (matcher.find()) {
			return matcher.group();
		}
		return null;
	}

    private static boolean match(String s, String s1) {
        while (s1 == null || s == null)
            return false;
        return Pattern.compile(s).matcher(s1).matches();
    }

    private static final String userName_regx = "^[a-zA-Z][a-zA-Z0-9_]*$";
    private static final String mobile_regx = "^[1][3-8]+\\d{9}";
    private static final String email_regx = "^(\\w)+(\\.\\w+)*@(\\w)+((\\.\\w{2,3}){1,3})$";
    private static final String password_regx = "^[a-zA-Z0-9]{6,10}$";
	private static final String digital_regx = "^[0-9]{6,10}$";
	private static final String letters_regx = "^[a-zA-Z]{6,10}$";
    private static final String url_regx = "(http://|ftp://|https://|www){0,1}[^\u4e00-\u9fa5\\s]*?\\.(com|net|cn|me|tw|fr)[^\u4e00-\u9fa5\\s]*";
    private static final String special_regx = "[\u4e00-\u9fa5]*[a-z]*[A-Z]*\\d*-*_*\\s*";
    private static final String userRealName_regx = "[\u4e00-\u9fa5]*[a-z]*[A-Z]*";
	private static final String bankCard_regx = "^\\d{16,19}$|^\\d{6}[- ]\\d{10,13}$|^\\d{4}[- ]\\d{4}[- ]\\d{4}[- ]\\d{4,7}$";

    public static boolean validateAccount(String account) {
        return match(userName_regx, account);
    }

    public static boolean validateMobile(String mobile) {
        return match(mobile_regx, mobile);
    }

    public static boolean validateEmail(String email) {
        return match(email_regx, email);
    }

    public static boolean validateUserName(String input) {
        return validateAccount(input) || validateMobile(input) || validateEmail(input);
    }

    public static boolean validatePassword(String input) {
        return match(password_regx, input);
    }

    public static boolean validateUrl(String input) {
        return match(url_regx, input);
    }

    public static boolean validateSpecial(String input) {
    	return match(special_regx, input);
	}

    public static boolean validateRealName(String input) {
    	return match(userRealName_regx, input);
	}

	public static boolean validatePassWordStrength(String input){
		return match(digital_regx, input) || match(letters_regx, input);
	}

	public static boolean validateBankCard(String input) {
		return match(bankCard_regx, input);
	}

}
